<?php
class App_Activity extends Data_Item
{
    public function __construct($activityId = NULL)
    {
        $this->_commTableName = 'mod_activity';
        $this->_commPrimaryKey = 'id';
        $this->_activityId = (int) $activityId;
        $this->_nid     = $this->_activityId;
    }

    // 活动详情
    public function detail ($activityId = NULL)
    {
        // 活动信息
        $activityId = $activityId > 0 ? $activityId : $this->_activityId;
        $detail  = parent::detail($activityId);
        $detail['images'] = explode('|', $detail['images']);

        // 导游信息
        $guider  = new Guider(Arr::get($detail, 'uid'));
        $detail['guider'] = $guider->getUserInfo();

        return $detail;
    }

    // 删除活动
    public function remove ($activityId = NULL)
    {
        $activityId = $activityId > 0 ? $activityId : $this->_activityId;
        $this->update(array(
            'changed' => DB::expr('unix_timestamp(now())'),
            'status'  => 'INVALID',
        ), array('id', '=', $activityId));
    }


    // 分类下的活动列表
    public function listByCategory ($catId, $offset = 0, $limit = 10)
    {
        $counts = DB::select(array('count("id")', 'counts'))
            ->from('tiyu_categorygl')
            ->where('categoryId', '=', $catId)
            ->execute()
            ->get('counts');

        if ($counts == 0)
            return array(0, array());

        $query = DB::select('targetType', 'targetNid')
            ->from('tiyu_categorygl')
            ->where('categoryId', '=', $catId)
            ->order_by('sort', 'asc')
            ->offset($offset)
            ->limit($limit)
            ->execute();

        // 活动ID
        $ids = array();
        foreach ($query as $rs)
            $ids[] = $rs['targetNid'];

        $query = DB::select()
            ->from('mod_activity')
            ->where('status', '=', 'VALID')
            ->where('id', 'in', $ids);

        if ($limit > 0)
        {
            $query->offset($offset)->limit($limit);
        }

        $query  = $query->execute();

        $acts = array();
        foreach ($query as $rs)
        {
            $guider = new Guider($rs['uid']);
            $rs['guider'] = $guider->getUserInfo();
            $acts[] = $rs;
        }

        return array($counts, $acts);
    }

    // 路线搜索
    public function search ($guiderUid = NULL, $offset = 0, $limit = 10, $catId = NULL)
    {
        $count = DB::select(array('count("id")', 'counts'))
            ->from('mod_activity')
            ->where('status', '=', 'VALID');
            
        $query = DB::select()
            ->from('mod_activity')
            ->where('status', '=', 'VALID');


        if ($limit > 0)
        {
            $query->offset($offset)->limit($limit);
        }

        if ($guiderUid > 0)
        {
            $count->where('uid', '=', $guiderUid);
            $query->where('uid', '=', $guiderUid);
        }

        $counts = $count->execute()->get('counts');
        $query  = $query->execute();

        $acts = array();
        foreach ($query as $rs)
        {
            $guider = new Guider($rs['uid']);
            $rs['guider'] = $guider->getUserInfo();
            $acts[] = $rs;
        }

        return array($counts, $acts);
    }

    // 更新活动的预定订单数量
    // 状态为1, 3, 7, 99是有效订单
    public function updateCountsOrders ($n = NULL)
    {
        // $n 参数作废

        // 获取实际订单数
        $counts = DB::select(array('count("id")', 'counts'))
            ->from('app_order')
            ->where('goodsType', '=', 'ACTIVITY')
            ->where('goodsId', '=', $this->_activityId)
            ->where('status', 'in', array(1, 3, 7, 99))
            ->execute()
            ->get('counts');

        DB::update('mod_activity')
            ->set(array('orders' => $counts))
            ->where('id', '=', $this->_activityId)
            ->execute();
    }

    public function getGuiderUid ()
    {
        return $this->getByKey('uid');
    }

    public function getMoney ($startDay, $stopDay, $persons)
    {
        $price   = $this->getPrice();
        $days    = Util_Date::days($startDay, $stopDay);

        // 活动订单价格是 单价*人头数
        return $price * $persons * 1.1;
    }

    public function getPrice ($humanRead = FALSE, $alldays = TRUE)
    {
        $service = $this->getByKey('priceService');
        $days    = 1;

        if ($alldays)
            $n = $days * $service;
        else
            $n = $service;

        if ($humanRead)
            return number_format($n / 100, 2);
        else
            return $n;
    }

    public function getName ()
    {
        return $this->getByKey('name');
    }

    public function getCurrentGuiderFreeDays ()
    {
        $freeDays = $this->getByKey('freeTimeDays');
        $persons  = $this->getByKey('serviceMaxPersons');
        $freeDays = explode(',', $freeDays);
        $days     = array();
        $today    = strtotime(date("Y-m-d"));
        foreach ($freeDays as $d)
        {
            $d = trim($d);
            if (! empty($d))
                $days[] = $d;
        }

        foreach ($days as $k => $day)
        {
                $t = strtotime($day);

                if ($t < $today)
                    unset($days[$k]);
        }

        $query = DB::select('startDay', 'stopDay', 'persons')
            ->from('app_order')
            ->where('goodsType', '=', 'ACTIVITY')
            ->where('goodsId', '=', $this->_activityId)
            ->where('status', '=', 3)
            ->execute();

        $ordDays = array();
        foreach ($query as $rs)
        {
            $day = $rs['startDay'];
            if (isset($ordDays[$day]))
                $ordDays[$day] += $rs['persons'];
            else
                $ordDays[$day] = $rs['persons'];
        }

        $ret = array();
        foreach ($days as $k => $day)
        {
            if (in_array($day, array_keys($ordDays)))
            {
                if ($persons > $ordDays[$day])
                    $ret[$day] = $persons - $ordDays[$day];
            }
            else
                $ret[$day] = $persons;
        }

        return $ret;
    }


    public function getByKey($key)
    {
        if (empty($this->_info))
        {
            $this->_info = DB::select()
                ->from('mod_activity')
                ->where('id', '=', $this->_nid)
                ->execute()
                ->current();
        }

        return Arr::get($this->_info, $key);
    }

    public function getDaysService()
    {
        $item = $this->record($this->_activityId);
        $startDay = Arr::get($item, 'startDay');
        $stopDay  = Arr::get($item, 'stopDay');

        return (int) Arr::get($item, 'days');
    }

    public function canRequestSubmittedPrize ($uid)
    {
        $popu = new Popularize;
        if ($popu->userHasGotFirstSubmittedPrize($uid))
            return FALSE;
        else
            return TRUE;

        // DEBUG
        if ($this->isFirstSubmitted())
        {
            $popu = new Popularize;
            if ($popu->userHasRequestFirstSubmittedPrize($uid))
                return FALSE;
            else
                return TRUE;
        }

        return FALSE;
    }

    // 判断是否是一个发布的活动
    public function isFirstSubmitted()
    {
        $query = DB::select('id')
            ->from('mod_activity')
            ->limit(1)
            ->order_by('created', 'asc')
            ->execute()
            ->get('id');

        $activityId = (int) $query;
        if ($activityId > 0 && $activityId == $this->_activityId)
            return TRUE;
        else
            return FALSE;
    }
}
